/**
 * Project Name:Micro-Services-Codec-Msgpack
 * File Name   :SerializationWithoutAnnotations.java
 * Package Name:com.micro.services.codec.msgpack
 * Date:2015-9-6下午3:22:24
 * Copyright (c) 2015, http://my.oschina.net/httpssl All Rights Reserved.
 *
 */
/**
 *  {{Code Template Comments Files}}
 */

package com.micro.services.codec.msgpack;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.msgpack.MessagePack;
import org.msgpack.annotation.Optional;
import org.msgpack.packer.Packer;
import org.msgpack.unpacker.Unpacker;

/**
 * ClassName:SerializationWithoutAnnotations <br/>
 * Function :TODO ADD FUNCTION. <br/>
 * Reason :不使用@Message来达到msgpack序列化 <br/>
 * Date :2015-9-6 下午3:22:24 <br/>
 * 
 * @author :http://my.oschina.net/httpssl
 * @email :491835898@QQ.COM
 * @since :JDK 1.7
 * @see For example, if MyMessage2 class is included in external library, you
 *      cannot easily modify the class declaration and append @Message to it.
 *      register method allows to generate a pair of serializer and deserializer
 *      for MyMessage2 class automatically. You can serialize objects of
 *      MyMessage2 class after executing the method.
 */
public class SerializationWithoutAnnotations
{
	/*
	 * 使用private声明将无法识别
	 */
	public static class MyMessage2{
		private int id;
		private String name;
		private List<MyMessage2> data=new LinkedList<MyMessage2>();
		 // new field
		//If you try to deserialize the old version data, optional fields will be ignored.
		//意思就是,如果你用当前这个带了flag的类去 识别旧的数据,这个用optional标识的属性会被忽略,不会报错
	    @Optional
	    public int flag = 0;
		@Override
		public String toString() {
			return "MyMessage2 [id=" + id + ", name=" + name + ", data=" + data + ", flag=" + flag + "]";
		}
	}
	
	public static void main(String[] args) throws IOException {
		MessagePack msgpack = new MessagePack();
		msgpack.register(MyMessage2.class);
		
		MyMessage2 m = new MyMessage2();
		m.name = "mm2";
		m.id = 1000000;
		for(int i=1;i<10;i++){
			MyMessage2 i1 = new MyMessage2();
			i1.id = i;
			i1.name = "name "+i;
			m.data.add(i1);
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
        Packer packer = msgpack.createPacker(out);
        packer.write(m);
        byte[] bytes = out.toByteArray();
        //
        // DESERIALIZE
        //
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        Unpacker unpacker = msgpack.createUnpacker(in);
        MyMessage2 dst1 = unpacker.read(MyMessage2.class);
        System.out.println(dst1);
	}
}